package com.im.app.controller;


import com.im.app.model.Admin;
import com.im.app.model.User;
import com.im.app.utils.JsonUtil;
import org.jim.core.ImChannelContext;
import org.jim.core.ImPacket;
import org.jim.core.cache.redis.JedisTemplate;
import org.jim.core.http.HttpRequest;
import org.jim.core.http.HttpResponse;
import org.jim.core.packets.Command;
import org.jim.core.packets.HttpReqBody;
import org.jim.server.JimServerAPI;
import org.jim.server.command.CommandManager;
import org.jim.server.command.handler.HttpReqHandler;
import org.jim.server.util.HttpResps;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class BaseController {

    public User getUser(String token) {
        User user = null;
        try {
             user = JedisTemplate.me().get(token, User.class);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return user;
    }

    public Admin getAdmin(String token){
        Admin admin = null;
        try {
            admin = JedisTemplate.me().get(token, Admin.class);
        } catch (Exception e) {
            return admin;
        }
        return admin;
    }

    public HttpResponse getHttPacket(HttpRequest request,HttpReqBody httpReqBody) throws Exception{
        List<ImChannelContext> list=JimServerAPI.getByUserId(httpReqBody.getOpUserId());
        if(!CollectionUtils.isEmpty(list)){
            ImPacket httpPacket = new ImPacket(Command.COMMAND_GET_HTTP_REQ,httpReqBody.toByte());
            HttpReqHandler httpReqHandler = CommandManager.getCommand(Command.COMMAND_GET_HTTP_REQ,HttpReqHandler.class);
            ImPacket imPacket=httpReqHandler.handler(httpPacket, list.get(0));
            return HttpResps.json(request, JsonUtil.byteArrayToJsonObject(imPacket.getBody()));
        }else {
            Map<String,Object> map=new HashMap<>();
            map.put("code",10023);
            map.put("msg","用户未登陆");
            map.put("command",22);
            return HttpResps.json(request, map);
        }
    }
}
